package rpcbase

import (
	"fmt"
	"gitee.com/851537/gbase"
	"github.com/google/uuid"
	"time"
)

type Token struct {
	gbase.Base
	Ts    int64  `json:"ts"`
	Nonce string `json:"nonce"`
	Md5   string `json:"md5"`
}

func (this *Token) GenMd5(secKey string) string {
	return gbase.Md5(fmt.Sprintf("%d%s%s", this.Ts, this.Nonce, secKey))
}

// 用于服务端校验密钥
func (this *Token) CheckMd5(secKey string) bool {
	return this.Md5 == this.GenMd5(secKey)
}

func (this *Token) ToString() string {
	return this.Base.ToString(this)
}

func NewToken() *Token {
	token := &Token{}
	return token
}

func NewTokenWithMd5(secKey string) *Token {
	token := &Token{}
	token.Ts = time.Now().UnixMilli()
	token.Nonce = uuid.NewString()
	token.Md5 = token.GenMd5(secKey)
	return token
}
